const loaderRegistry = new Map()

const createLoader = (key) => {
  let scriptEl = null
  let loadingPromise = null

  const removeScript = () => {
    if (scriptEl && scriptEl.parentNode) {
      scriptEl.parentNode.removeChild(scriptEl)
    }
    scriptEl = null
  }

  const load = () => {
    if (typeof window !== 'undefined' && window.T && window.T.Map) {
      return Promise.resolve(window.T)
    }

    if (loadingPromise) {
      return loadingPromise
    }

    loadingPromise = new Promise((resolve, reject) => {
      if (!key) {
        reject(new Error('Tianditu key is required'))
        return
      }

      const url = `https://api.tianditu.gov.cn/api?v=4.0&tk=${encodeURIComponent(key)}`
      scriptEl = document.createElement('script')
      scriptEl.type = 'text/javascript'
      scriptEl.src = url
      scriptEl.onload = () => {
        resolve(window.T)
      }
      scriptEl.onerror = (error) => {
        removeScript()
        loadingPromise = null
        reject(new Error('Failed to load Tianditu API: ' + error?.message || 'network error'))
      }
      document.head.appendChild(scriptEl)
    })

    return loadingPromise
  }

  const dispose = () => {
    removeScript()
    loadingPromise = null
  }

  return {
    load,
    dispose,
  }
}

export const useTiandituLoader = (key) => {
  if (!loaderRegistry.has(key)) {
    loaderRegistry.set(key, createLoader(key))
  }
  return loaderRegistry.get(key)
}

export default useTiandituLoader

